package com.qyhl.webtv.module_broke.scoop.mine;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.ScoopListBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.R2;
import com.qyhl.webtv.module_broke.utils.itemview.ScoopItemContract;
import com.qyhl.webtv.module_broke.utils.itemview.ScoopItemPresenter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;

/**
 * A simple {@link Fragment} subclass.
 */
public class ScoopMineFragment extends BaseFragment implements ScoopMineContract.ScoopMineView, ScoopItemContract.ScoopItemView {
    @BindView(R2.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;


    private ScoopMinePresenter mPresenter;

    private String brokeId = "0";

    private List<ScoopListBean> mDataList;

    private CommonAdapter mAdapter;

    private ScoopItemPresenter itemPresenter;

    public static ScoopMineFragment newIn(int isPrivate) {
        ScoopMineFragment scoopMineFragment = new ScoopMineFragment();
        Bundle bundle = new Bundle();
        bundle.putString("isPrivate", String.valueOf(isPrivate));
        scoopMineFragment.setArguments(bundle);
        return scoopMineFragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.broke_activity_scoop_topic, container, false);
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void create() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        mPresenter = new ScoopMinePresenter(this);
        itemPresenter = new ScoopItemPresenter(this);
        initView();
        setListeners();
        mPresenter.getMine(brokeId, Objects.requireNonNull(getArguments()).getString("isPrivate"));
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        BusFactory.getBus().register(this);

        titleLayout.setVisibility(View.GONE);

        mDataList = new ArrayList<>();

        //设置刷新
        refresh.setRefreshFooter(new ClassicsFooter(Objects.requireNonNull(getContext())));
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setDisableContentWhenRefresh(true);
        refresh.setDisableContentWhenLoading(true);
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mAdapter = new CommonAdapter<ScoopListBean>(getContext(), R.layout.broke_item_scoop_list, mDataList) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void convert(ViewHolder holder, final ScoopListBean bean, int position) {
                //设置用户信息
                ImageView headIcon = holder.getView(R.id.head_icon);

                TextView nickName = holder.getView(R.id.nickname);

                if (bean.getBrokeNews().getIsAnonymous() == 0) {
                    Glide.with(ScoopMineFragment.this)
                            .load(R.drawable.scoop_head_default)
                            .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                            .into(headIcon);

                    nickName.setText("匿名用户");
                } else {
                    Glide.with(ScoopMineFragment.this)
                            .load(bean.getBrokeNews().getCreatorAvatar())
                            .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default).optionalTransform(new GlideCircleTransform(getContext())))
                            .into(headIcon);
                    nickName.setText(bean.getBrokeNews().getAuthor());
                }

                //设置标题
                holder.setText(R.id.title, bean.getBrokeNews().getTitle());

                //设置时间
                TextView date = holder.getView(R.id.publish_date);
                date.setText(DateUtils.mTranslateDate(bean.getBrokeNews().getPublishtime()));//发布日期设置

                //设置关注人数
                holder.setText(R.id.like_num, bean.getAttention() + "人关注");

                //设置关注状态
                final TextView likeBtn = holder.getView(R.id.like_btn);
                if (bean.getIsAttention() == 0) {
                    likeBtn.setText("关注");
                    likeBtn.setTextColor(Objects.requireNonNull(getActivity()).getResources().getColor(R.color.global_base));
                    likeBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.drawable.scoop_like_on_icon), null, null, null);
                } else {
                    likeBtn.setText("已关注");
                    likeBtn.setTextColor(Objects.requireNonNull(getActivity()).getResources().getColor(R.color.global_black_lv1));
                    likeBtn.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.drawable.scoop_like_off_icon), null, null, null);
                }

                likeBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (likeBtn.getText().toString().equals("关注")) {
                            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                @Override
                                public void login(boolean isLogin) {
                                    if (isLogin) {
                                        itemPresenter.addAttention(bean.getBrokeNews().getId() + "");
                                    } else {
                                        Toast.makeText(getContext(), "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                        RouterManager.routerLogin(getActivity(), 300);
                                    }
                                }

                                @Override
                                public void error(String s) {

                                }
                            });
                        } else {
                            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                @Override
                                public void login(boolean isLogin) {
                                    if (isLogin) {
                                        itemPresenter.cancelAttention(bean.getBrokeNews().getId() + "");
                                    } else {
                                        Toast.makeText(getContext(), "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                        RouterManager.routerLogin(getActivity(), 300);
                                    }
                                }

                                @Override
                                public void error(String s) {

                                }
                            });
                        }
                    }
                });

                //设置主题
                TextView topicTitle = holder.getView(R.id.topic_title);
                topicTitle.setText("#" + bean.getBrokePlate().getName() + "#");
                topicTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getBrokePlate().getId() + "");
                        bundle.putString("title", bean.getBrokePlate().getName());
                        RouterManager.router(ARouterPathConstant.SCOOP_TOPIC, bundle);
                    }
                });

                //设置摘要
                TextView summary = holder.getView(R.id.summary);
                if (StringUtils.isEmpty(bean.getBrokeNews().getContent())) {
                    summary.setVisibility(View.GONE);
                } else {
                    summary.setVisibility(View.VISIBLE);
                    summary.setText(bean.getBrokeNews().getContent());
                }

                //设置内容
                switch (bean.getBrokeNews().getType()) {
                    case 0://图文
                        if (bean.getImages() != null && bean.getImages().size() > 0) {
                            holder.setVisible(R.id.content_layout, true);
                            holder.setVisible(R.id.picture_layout, true);
                            holder.setVisible(R.id.video_layout, false);

                            final RoundedImageView pic_one = holder.getView(R.id.pic_one);
                            final RoundedImageView pic_two = holder.getView(R.id.pic_two);
                            RoundedImageView pic_three = holder.getView(R.id.pic_three);
                            final RelativeLayout threeLayout = holder.getView(R.id.pic_three_layout);

                            switch (bean.getImages().size()) {
                                case 1:
                                    pic_one.setVisibility(View.VISIBLE);
                                    pic_two.setVisibility(View.INVISIBLE);
                                    threeLayout.setVisibility(View.INVISIBLE);

                                    Glide.with(getContext())
                                            .load(bean.images.get(0).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_one);
                                    break;
                                case 2:
                                    pic_one.setVisibility(View.VISIBLE);
                                    pic_two.setVisibility(View.VISIBLE);
                                    threeLayout.setVisibility(View.INVISIBLE);

                                    Glide.with(getContext())
                                            .load(bean.images.get(0).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_one);

                                    Glide.with(getContext())
                                            .load(bean.images.get(1).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_two);
                                    break;
                                case 3:
                                    pic_one.setVisibility(View.VISIBLE);
                                    pic_two.setVisibility(View.VISIBLE);
                                    threeLayout.setVisibility(View.VISIBLE);
                                    holder.setVisible(R.id.pic_num, false);

                                    Glide.with(getContext())
                                            .load(bean.images.get(0).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_one);

                                    Glide.with(getContext())
                                            .load(bean.images.get(1).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_two);

                                    Glide.with(getContext())
                                            .load(bean.images.get(2).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_three);
                                    break;
                                default:
                                    pic_one.setVisibility(View.VISIBLE);
                                    pic_two.setVisibility(View.VISIBLE);
                                    threeLayout.setVisibility(View.VISIBLE);
                                    holder.setVisible(R.id.pic_num, true);

                                    Glide.with(getContext())
                                            .load(bean.images.get(0).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_one);

                                    Glide.with(getContext())
                                            .load(bean.images.get(1).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_two);

                                    Glide.with(getContext())
                                            .load(bean.images.get(2).getThumbnailUrl())
                                            .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                                            .into(pic_three);

                                    holder.setText(R.id.pic_num, "+" + bean.getImages().size());
                                    break;
                            }
                            pic_one.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    MNImageBrowser.showImageBrowser(getContext(), pic_one, 0, getImageList(bean));
                                }
                            });
                            pic_two.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    MNImageBrowser.showImageBrowser(getContext(), pic_two, 1, getImageList(bean));
                                }
                            });
                            threeLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    MNImageBrowser.showImageBrowser(getContext(), threeLayout, 2, getImageList(bean));
                                }
                            });
                        } else {
                            holder.setVisible(R.id.content_layout, false);
                        }
                        break;
                    case 1://视频
                        holder.setVisible(R.id.content_layout, true);
                        holder.setVisible(R.id.picture_layout, false);
                        holder.setVisible(R.id.video_layout, true);

                        ImageView videoCover = holder.getView(R.id.video_cover);
                        ViewGroup.LayoutParams params = videoCover.getLayoutParams();
                        if (bean.getVideoCoverWidth() > bean.getVideoCoverHeight()) {
                            params.width = (bean.getVideoCoverWidth() > 600 || bean.getVideoCoverWidth() <= 0) ? 600 : bean.getVideoCoverWidth();
                            params.height = params.width * 9 / 16;
                        } else {
                            params.height = (bean.getVideoCoverHeight() > 600 || bean.getVideoCoverHeight() <= 0) ? 600 : bean.getVideoCoverHeight();
                            params.width = params.height * 9 / 16;
                        }
                        videoCover.setLayoutParams(params);
                        Glide.with(ScoopMineFragment.this).load(bean.getBrokeNews().getCoverImgUrl()).apply(new RequestOptions().error(R.drawable.video_list_portrait_default).placeholder(R.drawable.video_list_portrait_default)).into(videoCover);

                        RelativeLayout videoLayout = holder.getView(R.id.video_layout);
                        videoLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Bundle bundle = new Bundle();
                                bundle.putString(IntentKey_VideoUrl, bean.getBrokeNews().getUrl());
                                bundle.putString(IntentKey_VideoCover, bean.getBrokeNews().getCoverImgUrl());
                                RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
                            }
                        });
                        break;
                    default:
                        holder.setVisible(R.id.content_layout, false);
                        break;
                }


                //设置处理状态
                TextView status = holder.getView(R.id.status);
                switch (bean.getBrokeNews().getStatus()) {
                    case 2://未处理
                        status.setVisibility(View.GONE);
                        break;
                    case 21://处理中
                        status.setVisibility(View.VISIBLE);
                        status.setText("处理中");
                        status.setTextColor(Objects.requireNonNull(getActivity()).getResources().getColor(R.color.global_base));
                        break;
                    case 22://已处理
                        status.setVisibility(View.VISIBLE);
                        status.setText("已处理");
                        status.setTextColor(Objects.requireNonNull(getContext()).getResources().getColor(R.color.global_black_lv4));
                        break;
                    case 23:
                        status.setVisibility(View.GONE);
                        break;
                    default:
                        status.setVisibility(View.GONE);
                        break;
                }


                //设置地理位置
                TextView location = holder.getView(R.id.location);
                if (StringUtils.isEmpty(bean.getBrokeNews().getAddress())) {
                    location.setVisibility(View.GONE);
                } else {
                    location.setVisibility(View.VISIBLE);
                    location.setText(bean.getBrokeNews().getAddress());
                }
            }
        });
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                brokeId = "0";
                mPresenter.getMine(brokeId, Objects.requireNonNull(getArguments()).getString("isPrivate"));
            }
        });

        //加载
        refresh.setOnLoadMoreListener(refreshlayout -> mPresenter.getMine(brokeId, getArguments().getString("isPrivate")));

        //重载
        loadMask.setOnReloadListener(v -> {
            brokeId = "0";
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getMine(brokeId, getArguments().getString("isPrivate"));
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", mDataList.get(position).getBrokeNews().getId() + "");
                RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }

    /**
     * 设置数据
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setData(List<ScoopListBean> beanList, boolean isMore) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        if (isMore) {
            mDataList.addAll(beanList);
        } else {
            mDataList.clear();
            mDataList.addAll(beanList);
        }

        mAdapter.notifyDataSetChanged();
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setErrorText(msg);
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setNoNetworkText(msg);
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setEmptyText(msg);
    }

    /**
     * toast
     *
     * @param msg
     */
    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Toasty.normal(getContext(), msg).show();
    }

    /**
     * log
     *
     * @param msg
     */
    @Override
    public void showLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Log.i("scoop_topic", msg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshMessage(Event.refreshMessage event) {
        if (event != null) {
            ScoopListBean bean = event.getBean();
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getBrokeNews().getId() == bean.getBrokeNews().getId()) {
                    mDataList.get(i).setIsAttention(bean.getIsAttention());
                    mDataList.get(i).setAttention(bean.getAttention());
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }


    private ArrayList<String> getImageList(ScoopListBean bean) {
        ArrayList<String> result = new ArrayList<>();
        for (int i = 0; i < bean.getImages().size(); i++) {
            result.add(bean.getImages().get(i).getUrl());
        }
        return result;
    }

    @Override
    public void setAddAttention(boolean isSuccess, String ID) {
        if (isSuccess) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getBrokeNews().getId() == Integer.parseInt(ID)) {
                    int num = mDataList.get(i).getAttention() + 1;
                    mDataList.get(i).setAttention(num);
                    mDataList.get(i).setIsAttention(1);
                    mAdapter.notifyItemChanged(i);
                    return;
                }
            }
        } else {
            Toasty.normal(Objects.requireNonNull(getContext()), "关注失败，请稍后再试！").show();
        }
    }

    @Override
    public void setCancelAttention(boolean isSuccess, String ID) {
        if (isSuccess) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getBrokeNews().getId() == Integer.parseInt(ID)) {
                    int num = mDataList.get(i).getAttention() - 1;
                    mDataList.get(i).setAttention(num);
                    mDataList.get(i).setIsAttention(0);
                    mAdapter.notifyItemChanged(i);
                    return;
                }
            }
        } else {
            Toasty.normal(Objects.requireNonNull(getContext()), "取关失败，请稍后再试！").show();
        }
    }
}
